<?php
/*
 * Update information about a user.
 */

// authenticate user first
F3::call('authentication.php');
if (F3::exists('auth_error'))
{
  // authentication failed
  return;
}

// get user ID from session
$id = F3::get('SESSION.user_id');

// read PUT data
parse_str(file_get_contents("php://input"), $put_vars);

// check if we have both a new and an old password (to change password)
if (isset($put_vars['new_password']) && !isset($put_vars['old_password']))
{
  // cannot set new password without the old one
  header('HTTP/1.1 500 Internal Server Error');
  header("Content-Type: application/json");
  $err = array("error_message" => "Setting new password requires old password as well.");
  echo json_encode($err);
  return;
}

if (isset($put_vars['old_password']) && isset($put_vars['new_password']))
{
  // check old password first
  $param = array('1' => $id);
  $res = DB::sql("SELECT password FROM user WHERE id=?", $param);
  if (count($res) == 0)
  {
    // cuold not find user
    header('HTTP/1.1 403');
    header("Content-Type: application/json");
    $err = array("error_message" => "Authentication failed.");
    echo json_encode($err);
    return;
  }

  // get password hash
  $row = $res[0];
  $hash = $row['password'];

  // get hasher
  // base-2 logarithm of the iteration count used for password stretching
  $hash_cost_log2 = 8;
  // make hashes non-portable to older systems
  $hash_portable = FALSE;
  // get hasher
  $hasher = new PasswordHash($hash_cost_log2, $hash_portable);

  // check old password
  if (!$hasher->CheckPassword($put_vars['old_password'], $hash)) {
    // old password does not match
    header('HTTP/1.1 403');
    header("Content-Type: application/json");
    $err = array("error_message" => "Authentication failed.");
    echo json_encode($err);
    return;
  }
  // old password matches

  // update hash
  $hash = $hasher->HashPassword($put_vars['new_password']);
  if (strlen($hash) < 20)
  {
    // could not hash password
    header('HTTP/1.1 500 Internal Server Error');
    header("Content-Type: application/json");
    $err = array("error_message" => "Internal error.");
    echo json_encode($err);
    return;
  }
  unset($hasher);

  // update hash in DB
  $param = array('1' => $hash, '2' => $id);
  DB::sql("UPDATE user SET password = ? WHERE id = ?", $param);
}

// update user information
$fields = array('fname', 'lname', 'nickname', 'dob', 'gender', 'SelfDescription');
foreach ($fields as $field)
{
  if (isset($put_vars[$field]))
  {
    // optional field exists, update user
    $param = array('1' => $put_vars[$field], '2' => $id);
    DB::sql("UPDATE user SET $field = ? WHERE id = ?", $param);
  }
}

header('HTTP/1.1 204');
header("Content-Type: application/json");
$response = "success";
echo json_encode($response);
return;
?>
